#include "cJSON/cJSON.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "app_common.h"
#include "log/log.h"

char *app_message_charsToJson(char *chars, int chars_len)
{
    int conn_type = chars[0] - '0';
    int id_len = chars[1] - '0';
    int msg_len = chars[2] - '0';
    if(chars_len != (id_len + msg_len + 3)) return NULL;
    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, "conn_type", conn_type);
    char *id = App_Common_CharsToHex(chars + 3, id_len);
    cJSON_AddStringToObject(json, "id", id);
    char *msg = App_Common_CharsToHex(chars + 3 + id_len, msg_len);
    cJSON_AddStringToObject(json, "msg", msg);
    char *json_str = cJSON_PrintUnformatted(json);
    cJSON_Delete(json);
    free(id);
    free(msg);
    return json_str;
}

int app_message_jsonToChars(char *json, char *chars_buff, int buff_len)
{
    int Data_Lenth = 0;
    cJSON *json_obj = cJSON_Parse(json);
    if(json_obj == NULL) return -1;
    cJSON *conn_type = cJSON_GetObjectItem(json_obj, "conn_type");
    cJSON *id = cJSON_GetObjectItem(json_obj, "id");
    cJSON *msg = cJSON_GetObjectItem(json_obj, "msg");
    if(cJSON_IsString(id) && cJSON_IsString(msg))
    {
        Data_Lenth = 3 + strlen(id->valuestring) / 2 + strlen(msg->valuestring) / 2;
    }
    if(Data_Lenth > buff_len)
    {
        log_error("buff_len is too small");
        return -1;
    }
    int id_len = strlen(id->valuestring) - 1;
    int msg_len = strlen(msg->valuestring) - 1;
    chars_buff[0] = conn_type->valueint + '0';
    chars_buff[1] = strlen(id->valuestring) / 2 + '0';
    chars_buff[2] = strlen(msg->valuestring) / 2 + '0';
    char *id_chars =  App_Common_HexToChars(id->valuestring, id_len);
    memcpy(chars_buff + 3, id_chars, id_len);
    free(id_chars);
    char *msg_chars = App_Common_HexToChars(msg->valuestring, msg_len);
    memcpy(chars_buff + 3 + strlen(id->valuestring) / 2, msg_chars, msg_len);
    free(msg_chars);
    chars_buff[Data_Lenth] = '\0';
    return Data_Lenth;
}

void App_message_Free(char *str)
{
    free(str);
}
